<template>
  <a-layout>
    <a-layout-content style="padding: 24px 50px; min-height: 280px;">
      <a-row :gutter="24">
        <a-col :span="16">
          <a-space size="4">
            <a-button type="primary" @click="add" size="large">新增</a-button>
          </a-space>
          <a-table
              v-if="level1.length > 0"
              :data-source="level1"
              :row-key="record => record.id"
              :loading="loading"
              :pagination="false"
              :defaultExpandAllRows="true"
              size="small"
              @change="handleTableChange"
          >
            <a-table-column title="名称" data-index="name" >
                  <template v-slot="{text, record}">
                    {{record.sort}} {{text}}
                  </template>
            </a-table-column>
<!--            <a-table-column title="父文档" data-index="parent" v-slot="{record}">-->
<!--              {{ getCategoryName(record.parent) }}-->
<!--            </a-table-column>-->
<!--            <a-table-column title="顺序" data-index="sort" ></a-table-column>-->
            <a-table-column title="操作" key="action" >
              <template v-slot="{text, record}">
                <a-space size="small">
                  <a-button type="primary" @click="edit(record)" size="small">编辑</a-button>
                  <a-popconfirm
                      title="确认要删除吗？删除后不可恢复"
                      ok-text="是"
                      cancel-text="否"
                      @confirm="handleDelete(record)"
                  >
                    <a-button type="primary" danger size="small">删除</a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </a-table-column>
          </a-table>
        </a-col>
        <a-col :span="8">
          <a-form :model="doc" :label-col="{span: 6}" :wrapper-col="{span:22}" layout="vertical">
            <a-form-item>
              <a-input v-model:value="doc.name" placeholder="名称" />
            </a-form-item>
            <a-form-item >
              <a-tree-select
                  v-model:value="doc.parent"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeSelectData"
                  placeholder="请选择父文档"
                  tree-default-expand-all
                  :field-names="{
                    children: 'children',
                    label: 'name',
                    value: 'id',
                  }"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model:value="doc.sort" placeholder="请输入顺序"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handlePreView" size="large">
                 <EyeOutlined />内容预览
              </a-button>
            </a-form-item>
            <a-form-item>
              <div style="border: 1px solid #ccc">
                <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                />
                <Editor
                    style="height: 500px; overflow-y: hidden;"
                    :defaultConfig="editorConfig"
                    v-model="valueHtml"
                    :mode="mode"
                    @onCreated="handleCreated"
                />
              </div>
            </a-form-item>
            <p>
              <a-button type="primary" @click="handleSave">保存</a-button>
            </p>
          </a-form>
        </a-col>
      </a-row>

      <a-drawer
          v-model:visible="drawerVisible"
          class="custom-class editor-content-view"
          title="内容预览"
          placement="right"
          width="80%"
          :headerStyle="{ backgroundColor: '#ccc' }"
      >
        <div v-html="valueHtml"></div>
      </a-drawer>
    </a-layout-content>
  </a-layout>

<!--  <a-modal-->
<!--      title="文档表单"-->
<!--      v-model:visible="editVisible"-->
<!--      :confirm-loading="editConfirmLoading"-->
<!--      @ok="editHandleOk"-->
<!--      okText="提交"-->
<!--      cancelText="取消"-->
<!--  >-->
<!--  </a-modal>-->
</template>

<script>
import {SmileOutlined, DownOutlined, ExclamationCircleOutlined, EyeOutlined } from '@ant-design/icons-vue';
import {defineComponent, ref, createVNode, shallowRef} from 'vue';
import axios from 'axios'
import {message, Modal} from 'ant-design-vue';
import {Tool} from "@/util/tool.ts";
import {useRoute} from "vue-router";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default defineComponent({
  name: "AdminDoc",
  setup() {
    const route = useRoute();
    const ebookId = route.query.ebookId;
    // console.log("route.path", route.path);
    // console.log("route.query", route.query);
    // console.log("route.param", route.params);
    // console.log("route.fullPath", route.fullPath);
    // console.log("route.name", route.name);
    // console.log("route.meta", route.meta);
    const docs = ref();
    const param = ref({});
    const loading = ref(false);

    const level1 = ref([]);
    const treeSelectData = ref([]);
    // 查询所有数据
    const handleQuery = (params) => {
      loading.value = true;
      params.ebookId = ebookId;
      axios.get("/doc/list", {params}).then((response) => {
        const data = response.data;
        loading.value = false;
        if (data.code == 200){
          docs.value = data.data;
          level1.value = Tool.array2Tree(docs.value, 0);
          treeSelectData.value = Tool.copy(level1.value);
          treeSelectData.value.unshift({id :0, name: '无'});
        } else {
           message.error(data.message)
        }
      });
    };
    const handleTableChange = (pagination) =>{
        handleQuery();
    }

    // 编辑
    const doc = ref({});

    const handleSave = () =>{
      doc.value.content = editorRef.value.getHtml();
      axios.post("/doc/save", doc.value).then( (resp) => {
        if (resp.data.code == 200) {
          message.info("操作成功");
          handleQuery({});
        } else{
          message.error(resp.data.message)
        }
      })
    }

    const edit = (record) => {
      doc.value = Tool.copy(record);
      treeSelectData.value = Tool.copy(level1.value);
      setDisable(treeSelectData.value, record.id);
      treeSelectData.value.unshift({id :0, name: '无'});
      handleQueryContent();
    }

    const add = () => {
      editorRef.value.setHtml('');
      doc.value = { ebookId: route.query.ebookId};
      treeSelectData.value = Tool.copy(level1.value);
      treeSelectData.value.unshift({id :0, name: '无'});
    }

    const ids = [];
    const names = [];
    const handleDelete = (record) => {
        let id = record.id;
        ids.length = 0;
        names.length = 0;
        getIds(level1.value, id);

        Modal.confirm({
          title: '重要提醒',
          icon: createVNode(ExclamationCircleOutlined),
          content: '将删除 【' + names + "】, 删除后不可恢复，确认要删除吗？",
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',

          onOk() {
            axios.delete("/doc/batchdelete?ids="+ids ).then( (resp) => {
              if (resp.data.code == 200) {
                handleQuery();
              } else {
                message.error("删除失败")
              }
            })
          },
        });

    }

    const onSearch = (name) => {
      handleQuery({
        name
      })
    }

    const getCategoryName = (id) => {
      let result = "";
      level1.value.forEach( (e) => {
        if (e.id == id){
          result = e.name;
        }
      });
      return result || ""; // == "" ? "无" : result;
    }

    const setDisable = (treeSelectData, id) =>{
        for (let i = 0; i < treeSelectData.length; i ++){
          const node = treeSelectData[i];
          if (node.id == id){
            node.disabled = true;
            if (node.children){
              for (let j = 0; j < node.children.length; j++){
                setDisable(node.children, node.children[j].id);
              }
            }
          } else {
            if (node.children){
              for (let j = 0; j < node.children.length; j++){
                setDisable(node.children, id);
              }
            }
          }
        }
    }


    const getIds = (treeSelectData, id) =>{
      for (let i = 0; i < treeSelectData.length; i ++){
        const node = treeSelectData[i];
        if (node.id == id){
          ids.push(id);
          names.push(node.name)
          if (node.children){
            for (let j = 0; j < node.children.length; j++){
              getIds(node.children, node.children[j].id);
            }
          }
        } else {
          if (node.children){
            for (let j = 0; j < node.children.length; j++){
              getIds(node.children, id);
            }
          }
        }
      }
    }

    const handleQueryContent = () => {
      loading.value = true;
      axios.get("/content/get/" + doc.value.id).then((response) => {
        const data = response.data;
        loading.value = false;
        if (data.code == 200){
          valueHtml.value = data.data.content;
          // editorRef.value.setHtml(data.data.content);
        } else {
          message.error(data.message)
        }
      });
    };

    // 富文本框
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('')

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    // 富文本框 创建完毕后
    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }
    
    // 抽屉
    const drawerVisible = ref(false);

    const handlePreView = () => {
      drawerVisible.value = true;
    }

    return {
      level1,
      loading,
      handleQuery,
      handleTableChange,
      handleSave,
      edit,
      doc,
      add,
      handleDelete,
      param,
      onSearch,
      getCategoryName,
      treeSelectData,
      route,
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      handlePreView,
      drawerVisible
    };
  },
  mounted() {
    let that = this;
    this.handleQuery({

    });
  },
  beforeUnmount() {
    const editor = this.editorRef.value
    if (editor == null) return
    editor.destroy();
  },

  components: {
    SmileOutlined,
    DownOutlined,
    Editor,
    Toolbar,
    EyeOutlined
  },
});

</script>


<style scoped>

</style>